﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
//using POS.Plugins;
using FCNS.Data;
using System.Collections.ObjectModel;

namespace POS
{
    public partial class MainWindow : Window
    {
        ObservableCollection<Table.PosOrderS> guaDanList = new ObservableCollection<Table.PosOrderS>();

        Table.UserS zengSongUserS = null;
        Int64 zengSongUserSId = -1;

        #region 模板相关 Login,Sale,Pay
        List<TempleteDefine> allTemplete = new List<TempleteDefine>();
        public List<TempleteDefine> AllTemplete
        {
            get { return allTemplete.FindAll(f => f.PosFlag.ToString() == DoubleHConfig.AppConfig.PosFlag); }
        }

        TempleteDefine currentTemplete = null;
        ILoginTemplete pLogin = null;
        static IPayTemplete pPay = null;
        static ISaleTemplete pSale = null;

        private void InitTemplete()
        {
            allTemplete.Add(new TempleteDefine() { Name = "StoreTemplete", Text = "便利店", PosFlag = Table.PosS.EnumFlag.零售, IsTouch = false });
            allTemplete.Add(new TempleteDefine() { Name = "TouchTemplete", Text = "便利店(触摸屏)", PosFlag = Table.PosS.EnumFlag.零售, IsTouch = true });
            allTemplete.Add(new TempleteDefine() { Name = "WuJinTemplete", Text = "五金", PosFlag = Table.PosS.EnumFlag.五金, IsTouch = true });
        }

        private void LoadTemplete()
        {
            currentTemplete = allTemplete.FirstOrDefault(f => f.PosFlag.ToString() == DoubleHConfig.AppConfig.PosFlag && f.Name == DoubleHConfig.AppConfig.PosTempleteName);
            if (currentTemplete == null)
                currentTemplete = allTemplete.FirstOrDefault(f => f.PosFlag.ToString() == DoubleHConfig.AppConfig.PosFlag);

            Debug.Assert(currentTemplete != null, "模板丢失");
            switch (currentTemplete.Name)
            {
                case "TouchTemplete":
                    pLogin = new Templete.TouchTemplete.PageLogin();
                    pSale = new Templete.TouchTemplete.PageSale();
                    pPay = new Templete.TouchTemplete.PagePay();
                    break;

                case "WuJinTemplete":
                    pLogin = new Templete.WuJinTemplete.PageLogin();
                    pSale = new Templete.WuJinTemplete.PageSale();
                    pPay = (IPayTemplete)pSale;
                    break;

                default:
                    pLogin = new Templete.StoreTemplete.PageLogin();
                    pSale = new Templete.StoreTemplete.PageSale();
                    pPay = new Templete.StoreTemplete.PagePay();
                    break;
            }

            Debug.Assert(pLogin != null);
            Debug.Assert(pSale != null);
            Debug.Assert(pPay != null);
            ChangeUI(EnumUI.登陆);

            pLogin.Logined += (user, mode) => Logined(user, mode);

            pSale.Saled += new dSaleToPayEvent(Saled);
            pSale.ZengSong += new dZengSong(pSale_ZengSong);
            pSale.EditProduct += new dEditProduct(pSale_EditProduct);
            pSale.JiaoBan += new dNoParams(pSale_JiaoBan);
            pSale.GuaDan += new dGuaDan(pSale_GuaDan);
            pSale.TuiHuo += new dNoParams(ChangeMode);
            pSale.StoreS = Table.StoreS.GetObject(App.Pos.StoreSId);

            pPay.Payed += (ss, ee) => Payed(ss, ee);
        }


        private void Logined(Table.UserS ss, EnumMode ee)
        {
            if (DateTime.Now.Date < Table.SysConfig.SysConfigParams.LastLoginDate.Date)
            {
                if (Table.SysConfig.SysConfigParams.ForceVerificationDate)
                {
                    MessageWindow.Show("当前日期小于上一次登录的日期,禁止登录.");
                    return;
                }
                if (MessageWindow.Show("", "当前日期小于上一次登录的日期：" + Table.SysConfig.SysConfigParams.LastLoginDate.ToLongDateString() + "，继续吗？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;//还要检查是否月结日
            }
            if (!IsCurrentShift(ss))
                return;

            Table.UserS.LoginUser = ss;
            //以下内容必须放这里,因为如果用户没登陆,初始化DataGridColumns就会出错,它是调去用户配置文件的.
            DoubleHConfig.UserConfig = ConfigSerializer.LoadUserConfig(Table.UserS.LoginUser.Id);
            labelUserName.Content = Table.UserS.LoginUser.Name;
            pSale.Init();
            //Table.ErrorS.WriteLogFile(ss._LoginName + " 登陆成功");
            App.Pos.UpdateLastLoginDateTime(DateTime.Now);
            App.Mode = ee;
            labelSaleMode.Content = ee.ToString();
            ChangeUI(EnumUI.零售);
        }

        private void Saled()
        {
            Debug.Assert(App.Order != null);

            App.Order._UserSName = Table.UserS.LoginUser._LoginName;//新增的pos订单还没有用户名，此操作是为了打印的时候会显示用户名。
            ChangeUI(EnumUI.结账);
        }

        private void Payed(double money, bool isPayed)
        {
            if (isPayed)
            {
                SaveOrder(money);
                if (DoubleHConfig.AppConfig.PosIsPrint)
                    DoubleH.Utility.PrintFunction.PrintPosOrder(App.Order);

                pSale.OrderFinish(App.Order);
                App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                ChangeUI(EnumUI.零售);

                zengSongUserS = null;
                zengSongUserSId = -1;
            }
            else
                frame1.Navigate(pSale);
        }

        private void SaveOrder(double money)
        {
            App.Order.PosNO = App.Pos.PosNO;
            App.Order.StoreSId = App.Pos.StoreSId;
            App.Order.ZengSongUserSId = zengSongUserSId;
            if (App.Mode == EnumMode.退货模式)
            {
                Table.DataTableS.EnumDatabaseStatus result = App.Order.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    DoubleHConfig.AppConfig.PosCashboxMoney = DoubleHConfig.AppConfig.PosCashboxMoney - App.Order.Money;
                else
                    MessageWindow.Show(result.ToString());

                App.Mode = EnumMode.零售模式;
                labelSaleMode.Content = App.Mode;
            }
            else
            {
                Table.DataTableS.EnumDatabaseStatus result = App.Order.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    DoubleHConfig.AppConfig.PosCashboxMoney += App.Order.Money;
                else
                    MessageWindow.Show(result.ToString());
            }
        }

        private bool IsCurrentShift(Table.UserS newUser)
        {
            //检查交班状态
            App.CurrentShift = Table.PosShiftS.GetObjectNotShift(DoubleHConfig.AppConfig.PosNO);
            Table.UserS user = newUser;
            if (App.CurrentShift == null)
            {
                JiaoBanWindow jb = new JiaoBanWindow();
                jb.Init(true, false);
                jb.ShowDialog();
                if (!jb.Ensure)
                    return false;

                Table.PosShiftS pss = new Table.PosShiftS();
                pss.PosNO = DoubleHConfig.AppConfig.PosNO;
                pss.UserSId = user.Id;
                pss.StartDateTime = DateTime.Now;
                pss.StartMoney = jb.doubleUpDownMoney.Value.Value;
                pss.Insert();
                App.CurrentShift = pss;
            }
            else
            {
                if (user.Id != App.CurrentShift.UserSId)
                    if (MessageWindow.Show("", App.CurrentShift._UserSName + " 尚未交班,是否继续?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        return false;
            }
            return true;
        }

        #endregion

        #region 接口相关
        private void pSale_GuaDan(bool isTemp, bool addOrRemove, string flag)
        {
            if (isTemp)
                GuaDanIsTemp(addOrRemove, flag);
            else
                GuaDanNotTemp(addOrRemove, flag);

            pSale.GuaDanFinish(guaDanList);
        }
        private void GuaDanIsTemp(bool addOrRemove, string flag)
        {
            if (addOrRemove)
            {
                Debug.Assert(App.Order != null);

                if (guaDanList.FirstOrDefault(f => f._CorSVipNO == App.Vip.VipNO) != null)
                {
                    MessageWindow.Show("当前客户已存在挂单,不能再添加.");
                    return;
                }
                if(App.Vip!=null)
                App.Order._CorSVipNO = App.Vip.VipNO;

                guaDanList.Add(App.Order);
                App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                pSale.InitOrder();
                MessageWindow.Show("挂单成功");
            }
            else
            {
                App.Order = guaDanList.FirstOrDefault(f => f._CorSVipNO == flag);
                if (App.Order == null)
                {
                    int index = -1;
                    if (Int32.TryParse(flag, out index) && index >= 0 && index < guaDanList.Count)
                        App.Order = guaDanList[index];
                }

                if (App.Order != null)
                    guaDanList.Remove(App.Order);
                else
                {
                    MessageWindow.Show("挂单提取失败");
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                }

                pSale.InitOrder();
            }
        }
        private void GuaDanNotTemp(bool addOrRemove, string flag)
        {
            if (addOrRemove)
            {
                Table.DataTableS.EnumDatabaseStatus result;
                if (App.Order.CorSId == -1)
                {
                    MessageWindow.Show("客户不能为空");
                    return;
                }

                if (App.Order.Id == -1)
                {
                    App.Order.PosNO = App.Pos.PosNO;
                    App.Order.StoreSId = App.Pos.StoreSId;
                    App.Order.Enable = Table.PosOrderS.EnumEnable.记账;
                    result = App.Order.Insert();
                }
                else
                    result = App.Order.Update();

                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                {
                    MessageWindow.Show("挂单成功");
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                    pSale.InitOrder();
                }
                else
                    MessageWindow.Show(result.ToString());
            }
            else
                MessageWindow.Show("已记账单据禁止编辑");
        }

        private void pSale_JiaoBan()
        {
            if (Table.UserS.LoginUser == null)
                return;

            if (App.CurrentShift.UserSId != Table.UserS.LoginUser.Id)
            {
                MessageWindow.Show("当前班次属于 " + App.CurrentShift._UserSName + " 请重新登陆.");
                return;
            }
            if (MessageWindow.Show("", "确认交班吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            JiaoBanWindow jb = new JiaoBanWindow();
            jb.Init(false, false);
            jb.ShowDialog();
            if (jb.Ensure)
            {
                if (DoubleHConfig.AppConfig.PosIsPrintJiaoBan)
                {
                    PrintFunction.PrintPosJiaoBan(Table.UserS.LoginUser._LoginName, App.CurrentShift.PosNO, jb.doubleUpDownMoney.Value.Value.ToString(), jb.labelMoneySum.Content.ToString());
                }
                LogOff(false);
            }
        }

        private void pSale_ZengSong()
        {
            if (zengSongUserS == null && App.Order.ZengSongList.Count == 0)
                StartZengSong();
            else
                EndZengSong();
        }
        private void StartZengSong()
        {
            Debug.Assert(zengSongUserS == null);

            if (App.Mode != POS.EnumMode.零售模式)
            {
                MessageWindow.Show("退货模式不可赠送");
                return;
            }
            if (App.Order.ZengSongList.Count > 0)
            {
                MessageWindow.Show("一张单据只能做一次赠送");
                return;
            }

            DoubleH.Utility.TextInputWindow tiw = new TextInputWindow();
            tiw.Init("格式：账号.密码（例如:001.000000）", null, true);
            tiw.ShowDialog();
            string tiwText = tiw.Text;
            if (string.IsNullOrEmpty(tiwText) || !tiwText.Contains("."))
            {
                MessageWindow.Show("输入错误");
                return;
            }

            int index = tiwText.IndexOf('.', 0);
            zengSongUserS = Table.UserS.GetObject(tiwText.Substring(0, index), tiwText.Substring(index + 1));
            if (zengSongUserS == null || !zengSongUserS.HasAuthority(Table.PosS.EnumAuthority.赠送.ToString(), Table.UserS.EnumAuthority.查看))
            {
                MessageWindow.Show("权限不足");
                zengSongUserS = null;
                return;
            }

            MessageWindow.Show("赠送开始，重复点击可以结束赠送");
        }
        private void EndZengSong()
        {
            if (zengSongUserS == null)
                return;

            zengSongUserSId = zengSongUserS.Id;
            zengSongUserS = null;
            MessageWindow.Show("赠送结束");
        }

        private void pSale_EditProduct(EnumEditProduct eep, Table.ProductS product, double quantity, double price)
        {
            if (product == null)
            {
                MessageWindow.Show("请选择商品");
                return;
            }

            switch (eep)
            {
                case EnumEditProduct.添加: EditProductAdd(product); break;
                case EnumEditProduct.移除: EditProductRemove(product); break;
                case EnumEditProduct.编辑数量: EditProductQuantity(product, quantity); break;
                case EnumEditProduct.编辑价格: EditProductPrice(product, price); break;
            }
        }
        private void EditProductAdd(Table.ProductS product)
        {
            if (zengSongUserS != null)
            {
                Table.ProductS zsps = product.CloneObject(null) as Table.ProductS;
                Debug.Assert(zsps != null);
                zsps.Name += "(赠送)";
                zsps._TempPrice = 0;
                App.Order.ProductSList.Add(zsps);

                Table.ProductSInZengSongS zs = new Table.ProductSInZengSongS()
                {
                    ProductSId = product.Id,
                    Quantity = product._TempQuantity,
                    AveragePrice=product._AveragePrice
                };
                App.Order.ZengSongList.Add(zs);
                zsps._Tag = zs;//仅用于标识
            }
            else
            {
                product.InitPrice(App.Vip);
                App.Order.ProductSList.Add(product);
            }
        }
        private void EditProductRemove(Table.ProductS product)
        {
            if (zengSongUserS != null)
            {
                Table.ProductSInZengSongS zs = App.Order.ZengSongList.FirstOrDefault(f => f.ProductSId == product.Id);
                Table.ProductS pzs = App.Order.ProductSList.FirstOrDefault(f => f._Tag == zs);
                Debug.Assert(pzs != null);

                App.Order.ProductSList.Remove(pzs);
                App.Order.ZengSongList.Remove(zs);
            }
            else
            {
                if (product._Tag == null)
                    App.Order.ProductSList.Remove(product);
                else
                    MessageWindow.Show("非赠送模式下禁止移除赠品");
            }
        }
        private void EditProductQuantity(Table.ProductS product, double quantity)
        {
            Table.ProductSInZengSongS zs = App.Order.ZengSongList.FirstOrDefault(f => f.ProductSId == product.Id);
            if (zengSongUserS != null)
            {
                Table.ProductS pzs = App.Order.ProductSList.FirstOrDefault(f => f._Tag == zs);
                pzs._TempQuantity = quantity;
                zs.Quantity = quantity;
            }
            else
            {
                if (product._Tag == null)
                    product._TempQuantity = quantity;
                else
                    MessageWindow.Show("非赠送模式下禁止编辑数量");
            }
        }
        private void EditProductPrice(Table.ProductS product, double price)
        {
            if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.更改零售价) == Table.UserS.EnumAuthority.无权限)
            {
                MessageWindow.Show("权限不足");
                return;
            }

            Table.ProductSInZengSongS zs = App.Order.ZengSongList.FirstOrDefault(f => f.ProductSId == product.Id);
            if (zengSongUserS != null || product._Tag != null)
                MessageWindow.Show("赠送商品不能编辑价格");
            else
            {
                if (price <= 0)
                    MessageWindow.Show("价格必须大于 0");
                else
                    product._TempPrice = price;
            }
        }
        #endregion

        private void ChangeUI(EnumUI ui)
        {
            switch (ui)
            {
                case EnumUI.零售:
                    pSale.InitOrder();
                    frame1.Navigate(pSale);
                    break;

                case EnumUI.结账:
                    frame1.Navigate(pPay);
                    break;

                default:
                    frame1.Navigate(pLogin);
                    break;
            }
        }

        public void ChangeMode()
        {
            if (!(frame1.Content is ISaleTemplete))
                return;

            switch (App.Mode)
            {
                case EnumMode.零售模式:
                    if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.退货) == Table.UserS.EnumAuthority.无权限)
                    {
                        MessageWindow.Show("权限不足");
                        return;
                    }

                    App.Mode = EnumMode.退货模式;
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS退货单);
                    pSale.InitOrder();
                    break;

                case EnumMode.退货模式:
                    App.Mode = EnumMode.零售模式;
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                    pSale.InitOrder();
                    break;
            }
            labelSaleMode.Content = App.Mode;
        }

        private void OpenCashbox()
        {
            if (Table.UserS.LoginUser == null)
                return;
            if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.弹出钱箱) > Table.UserS.EnumAuthority.无权限)
            {
            }
            else
                MessageWindow.Show("权限不足");
        }

        private void CancelOrderByHotKey()
        {
            if (!(frame1.Content is ISaleTemplete))
                return;

            if (MessageWindow.Show("", "确定取消当前单据吗？", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                return;

            App.Mode = EnumMode.零售模式;
            labelSaleMode.Content = App.Mode;
            App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
            ChangeUI(EnumUI.零售);
        }

        public void LogOff(bool confirm)
        {
            if (confirm)
            {
                if ((frame1.Content is ILoginTemplete))
                    return;

                if (MessageWindow.Show("", "注销当前用户吗？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;
            }

            labelUserName.Content = "未登陆";
            labelSaleMode.Content = "";
            Table.UserS.LoginUser = null;
            App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
            frame1.Navigate(pLogin);
        }

        public void CloseThis()
        {
            bool close = true;
            foreach (Window w in this.OwnedWindows)
                if (w.IsActive)
                {
                    w.Close();
                    return;
                }

            if (close)
                this.Close();
        }

        /// <summary>
        /// 强制交班,仅能 InitDateTime 调用
        /// </summary>
        private void ForceJiaoBanNow()
        {
            if (DoubleHConfig.AppConfig.PosJiaoBan != DateTime.Now.ToString("HHmm"))
                return;

            JiaoBanWindow jb = new JiaoBanWindow();
            jb.Init(false, true);
            jb.ShowDialog();
            if (DoubleHConfig.AppConfig.PosIsPrintJiaoBan)
                PrintFunction.PrintPosJiaoBan(Table.UserS.LoginUser._LoginName, App.CurrentShift.PosNO, jb.doubleUpDownMoney.Value.Value.ToString(), jb.labelMoneySum.Content.ToString());

            LogOff(false);
        }
    }

    //public class ClassGuaDan
    //{
    //    public ClassGuaDan()
    //    {
    //        CorSId = MainWindow.pSale.CorSId;
    //        VipNO = MainWindow.pSale.VipNO;
    //        RemainIntegral = MainWindow.pSale.RemainIntegral;
    //        Flag = App.Order.Flag;

    //        StringBuilder sb = new StringBuilder();
    //        foreach (Table.ProductS ps in App.Order.ProductSList)
    //            sb.Append(ps.Id + "," + ps._TempPrice + "," + ps._TempQuantity + ";");

    //        ProductList = sb.ToString();
    //    }

    //    public Table.PosOrderS ToOrder()
    //    {
    //        Table.PosOrderS order = new Table.PosOrderS(Flag);
    //        order.CorSId = CorSId;
    //        foreach (string str in ProductList.Split(';'))
    //        {
    //            if (string.IsNullOrEmpty(str))
    //                continue;

    //            string[] s = str.Split(',');
    //            Table.ProductS ps = Table.ProductS.GetObject(Convert.ToInt64(s[0]));
    //            if (ps == null)
    //                continue;

    //            ps._TempPrice = Convert.ToDouble(s[1]);
    //            ps._TempQuantity = Convert.ToDouble(s[2]);
    //            order.ProductSList.Add(ps);
    //        }
    //        return order;
    //    }

    //    public Int64 CorSId { get; set; }
    //    public string VipNO { get; set; }
    //    public string RemainIntegral { get; set; }
    //    public string ProductList { get; set; }
    //    public Table.PosOrderS.EnumFlag Flag { get; set; }
    //    public string Text
    //    {
    //        get
    //        {
    //            return string.IsNullOrEmpty(VipNO) ? "挂单" : VipNO;
    //        }
    //    }
    //}
}